package cn.wjzhang.middle.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * ========================
 * 分页插件
 *
 * @author wjzhang
 * @version v1.0
 * ========================
 * @date 2023/6/29 15:09
 */
@Slf4j
@Configuration
public class MybatisPlusConfig implements MetaObjectHandler {

    /**
     * 分页插件
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 设置数据库类型，不同的数据库有不同的分页方式，默认为 MySQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 开启 count 的 join 优化，只针对部分 left join

        return interceptor;
    }

    /**
     * 创建人自动填充
     * @param metaObject 创建人自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
//        LoginInfo currentUser = LoginContextUtils.getCurrentUser();
//        if (ObjectUtil.isNotEmpty(currentUser)) {
//            this.strictInsertFill(metaObject, "createName", currentUser::getRealName, String.class);
//            this.strictInsertFill(metaObject, "createBy", currentUser::getUserId, String.class);
//        }
//        this.setFieldValByName( "createTime", DateUtil.date(), metaObject);
//        log.info("start insert fill {}", currentUser);
    }
//
    /**
     * 修改人自动填充
     * @param metaObject 创建人自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
//        LoginInfo currentUser = LoginContextUtils.getCurrentUser();
//        if (ObjectUtil.isNotEmpty(currentUser)) {
//            this.strictUpdateFill(metaObject, "updateName", currentUser::getRealName, String.class);
//            this.strictUpdateFill(metaObject, "updateBy", currentUser::getUserId, String.class);
//        }
//        this.setFieldValByName("updateTime", DateUtil.date(), metaObject);
//        log.info("start update fill {}", currentUser);
    }
}
